package com.example.timeemail;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.timeemail.Dao.UserDao;
import com.example.timeemail.Dialog.CustomDialog;
import com.example.timeemail.entity.User;
import com.example.timeemail.utils.LoginResult;
import com.example.timeemail.utils.OkHttpUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
    }
    //简单密码表
    String[] paws = new String[]
            {"123456","qwerty","asdfgh","zxcvbn","654321","234567","45678"};

    //邮箱判定
    public boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }


    //注册
    public void btn_submit_register_onclick(View view) {
        EditText etId = findViewById(R.id.et_reg_id);
        EditText etEmail = findViewById(R.id.et_reg_email);
        EditText etPassword = findViewById(R.id.et_reg_password);
        EditText etsuPassword = findViewById(R.id.et_reg_surePassword);


        if(etId.getText().toString().equals("") && etEmail.getText().toString().equals("") && etPassword.getText().toString().equals(""))
        {
            ToastShow("未输入任何信息，请进行输入");
            return;
        }
        if (etId.getText().toString().equals("")) {
            ToastShow("账号不能为空");
            return;
        }
        if(etId.getText().toString().length() < 3 || etId.getText().toString().length() > 8){
            ToastShow("用户名长度应为3-8位");
            return;
        }


        if (etEmail.getText().toString().equals("")) {
            ToastShow("邮箱不能为空");
            return;
        }
        if(!isEmail(etEmail.getText().toString())){
            ToastShow("请输入正确的邮箱");
            return;
        }

        if (etPassword.getText().toString().equals("")) {
            ToastShow("密码不能为空");
            return;
        }
        if(etPassword.getText().toString().length() < 4 || etPassword.getText().toString().length() > 8){
            ToastShow("密码长度应为4-8位");
            return;
        }

        boolean f = false;
        String paw = etPassword.getText().toString();

        for(int i = 0;i < paws.length; i++){
            if(paw.equals(paws[i]) ) {
                f = true;
                break;
            }
        }

        if(f){
            ToastShow("密码过于简单,为确保安全请重新输入");
            return;
        }

        if(etId.getText().toString().equals( etPassword.getText().toString() )){
            ToastShow("密码不能与用户名重复");
            return;
        }

        if(!etPassword.getText().toString().equals(etsuPassword.getText().toString())){
            ToastShow("两次输入的密码不一致，请确认密码");
            return;
        }


        CustomDialog customDialog = new CustomDialog(this, new CustomDialog.OnCustomDialogLister() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void btnConfirmLicenseClicked(boolean isConfirm) {
                if (isConfirm) {
                    sure_register(view);
                } else {

                    ToastShow("只有同意用户协议才能注册");
                }
            }

        });
        customDialog.show();
    }

    public void sure_register(View view) {
        EditText etId = findViewById(R.id.et_reg_id);
        EditText etEmail = findViewById(R.id.et_reg_email);
        EditText etPassword = findViewById(R.id.et_reg_password);
//
//        if (etId.getText().toString().equals("")) {
//            ToastShow("账号不能为空");
//            return;
//        }
//        if (etEmail.getText().toString().equals("")) {
//            ToastShow("邮箱不能为空");
//            return;
//        }
//        if (etPassword.getText().toString().equals("")) {
//            ToastShow("密码不能为空");
//            return;
//        }
        //添加至数据库
        registerWithOkHttp(etId.getText().toString(), etEmail.getText().toString(), etPassword.getText().toString());
    }

    //实现注册
    private void registerWithOkHttp(String account, String email, String password) {
        OkHttpUtil.registerWithOkHttp(account, email, password, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("RegisterActivity", "注册请求失败");
                ToastShow("注册请求失败：" + e.getLocalizedMessage());
            }

            //请求成功，获取服务器返回数据
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取返回内容
                final String responseData = response.body().string();
                //在主线程更新ui和响应用户操作
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoginResult result = new Gson().fromJson(responseData, LoginResult.class);
                        if (result.getStatus().equals("200")) {
                            ToastShow("注册成功");
                            Intent intent = new Intent(RegisterActivity.this, SigninActivity.class);
                            startActivity(intent);
                            /*
                            Intent intent=new Intent();
                            intent.putExtra("id",etId.getText().toString());
                            intent.putExtra("email",etEmail.getText().toString());
                            intent.putExtra("password",etPassword.getText().toString());
                            setResult(0,intent);*/
                            finish();
                        } else {
                            Toast.makeText(RegisterActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    void ToastShow(String context) {
        Toast toast = Toast.makeText(this, context, Toast.LENGTH_SHORT);
        View view = LayoutInflater.from(this).inflate(R.layout.toast_template, null);
        TextView TxtTaostContext = (TextView) view.findViewById(R.id.TxtTaostContext);
        TxtTaostContext.setText(context);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


}